﻿namespace WebPacker.Configuration
{
	using System;
	using System.Text;
	using NXml.Serialization.Mappings;
	using WebPacker.Filters;
	using WebPacker.Packs;
	using WebPacker.VersionGenerators;

	public class WebPackerMappingProvider : XmlMappingProvider
	{
		public override XmlMapping GetMapping(Type type)
		{
			if (type == typeof(PackInfo))
			{
				return new XmlObjectMapping(type)
				{
					XmlName = "pack",
					Properties = new XmlPropertyMapping[]
					{
						new XmlPropertyMapping(typeof(string), "Name")
						{
							XmlName = "name",
							MappingNode = XmlMappingNode.Attribute
						},
						new XmlPropertyMapping(typeof(PackType), "PackType")
						{
							XmlName = "type",
							MappingNode = XmlMappingNode.Attribute
						},
						new XmlPropertyMapping(typeof(string), "FilterName")
						{
							XmlName = "filter",
							MappingNode = XmlMappingNode.Attribute
						},
						new XmlPropertyMapping(typeof(string), "BasePath")
						{
							XmlName = "basePath",
							MappingNode = XmlMappingNode.Attribute
						},
						new XmlPropertyMapping(typeof(bool?), "Monitoring")
						{
							XmlName = "monitoring",
							MappingNode = XmlMappingNode.Attribute
						},
						new XmlPropertyMapping(typeof(string), "VersionGeneratorName")
						{
							XmlName = "versionGenerator",
							MappingNode = XmlMappingNode.Attribute
						},
						new XmlPropertyMapping(typeof(string), "Version")
						{
							XmlName = "version",
							MappingNode = XmlMappingNode.Attribute
						},
						new XmlPropertyMapping(typeof(ResourceInfo[]), "Resources")
						{
							XmlName = "resources"
						}
					}
				};
			}
			else if (type == typeof(ResourceInfo))
			{
				return new XmlObjectMapping(type)
				{
					XmlName = "item",
					Properties = new XmlPropertyMapping[]
					{
						new XmlPropertyMapping(typeof(string), "Name")
						{
							XmlName = "name",
							MappingNode = XmlMappingNode.InnerText
						},
						new XmlPropertyMapping(typeof(Encoding), "Encoding")
						{
							XmlName = "encoding",
							MappingNode = XmlMappingNode.Attribute
						}
					}
				};
			}
			else if (type == typeof(PackInfoCollection))
			{
				return new XmlCollectionMapping(type)
				{
					XmlItemName = "pack",
					SerializeItemType = false
				};
			}
			else if (type == typeof(ResourceInfo[]))
			{
				return new XmlCollectionMapping(type)
				{
					XmlItemName = "item",
					SerializeItemType = false
				};
			}
			else if (type == typeof(IFilter[]))
			{
				return new XmlCollectionMapping(type)
				{
					XmlItemName = "filter",
					SerializeItemType = true
				};
			}
			else if (type == typeof(IVersionGenerator[]))
			{
				return new XmlCollectionMapping(type)
				{
					XmlItemName = "versionGenerator",
					SerializeItemType = true
				};
			}

			return base.GetMapping(type);
		}
	}
}